package com.etlmaster.executor.utils;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.etlmaster.core.Configuration;
import com.etlmaster.core.DataSourceHolder;
import com.etlmaster.jdbc.JdbcTemplate;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class DataCollectionUtils {

	public static String mappEscapePath(String escapePath,
			Map<String, Object> data) {// 接口机转义替换
		return DpExecutorUtils.variableSubstitution(escapePath, data);
	}

	public static String fetchFtpSiteInfo(String ftpSite,
			JdbcTemplate jdbcTemplate) {

		String fetchSql;
		Map<String, Object> ftpInfo = null;
		String ftpSiteInfo = null;
		try {
			// sftp://username:password@hostName/remoteFilePath
			fetchSql = getProperties("fetchFtpServ");
			ftpInfo = (Map<String, Object>) jdbcTemplate.queryForMap(fetchSql,
					new Object[] { ftpSite });

			String ftptype = ftpInfo.get("ftptype").toString();
			String ip = ftpInfo.get("ip").toString();
			String username = ftpInfo.get("username").toString();
			String password = ftpInfo.get("password").toString();
			String port = ftpInfo.get("port").toString();
			ftpSiteInfo = String.format("%s://%s:%s@%s:%s/", ftptype, username,
					URLEncoder.encode(password, "UTF-8"), ip, port);
			// LOG.debug("从data_trans_database获取到团队编码({}) 数据源{} 用户({})
			// 密码:({})",teamCode,dsName,dbUserInfo.get("username").toString(),Encryption.decrypt(password));
		} catch (Exception e) {
			LogWriter.addLog("WARN",
					"严重告警：从data_trans_ftpserv未获取到 数据源{} 的信息,{}", ftpSite,
					e.getMessage());
		}
		return ftpSiteInfo;
	}
	@SuppressWarnings("unchecked")
	public static String initCrtTabMeta(String cfgStr,
			JdbcTemplate jdbcTemplate) {
		Map<String, Object> cfgObj = (Map<String, Object>) JsonHelper
				.getInstance().read(cfgStr);
		String xmlid = (String) cfgObj.get("xmlid");

		// 初始化表的扩展信息
		try {
			String fetchTableFileSql = Configuration.getInstance().getProperty(
					"fetchTableFileSql");
			if (fetchTableFileSql != null && fetchTableFileSql.length() > 0) {
				Map<String, Object> tableFile = (Map<String, Object>) jdbcTemplate
						.queryForMap(fetchTableFileSql, new Object[] { xmlid });

				cfgObj.putAll(tableFile);
			}else{
				LogWriter.addLog("ERROR","严重告警：从配置文件中未获取到fetchTableFileSql的值");
			}
		} catch (Exception e) {
			LogWriter.addLog("ERROR",
					"严重告警：从元数据表tablefile中未获取xmlid {} 的信息，请检查数据库名及模型名称.{}",
					xmlid, e.getMessage());
			return null;
		}
		// 初始化columns
		// 需要排序，通过唯一序号xmlid获取

		String fetchColumnSql = getProperties(
				"fetchColumnSql");
		if (fetchColumnSql != null && fetchColumnSql.length() > 0) {
			List<Map<String, Object>> columns;
			try {

				columns = jdbcTemplate.queryForList(fetchColumnSql,
						new Object[] { xmlid });
				if (columns != null && columns.size() != 0) {
					cfgObj.put("columns", columns);
				} else {
					LogWriter.addLog("WARN",
							"从元数据表column_val中未获取数据编号xmlID：{}的字段信息,{}", xmlid);
				}
			} catch (Exception e) {
				LogWriter.addLog("ERROR",
						"严重告警：从元数据表column_val中未获取数据编号xmlID：{}的字段信息,{}", xmlid,
						e.getMessage());
				return null;
			}
		} else {
			LogWriter.addLog("ERROR", "严重告警：从配置文件中获取fetchColumnSql失败");
		}
		return JsonHelper.getInstance().write(cfgObj);
	}

	public static Map<String, Object> getCreateTableMeta(String xmlid, JdbcTemplate jdbcTemplate) {
		Map<String, Object> cfgStr = new HashMap<String, Object>();
		cfgStr.put("xmlid", xmlid);

		String create = initCrtTabMeta(JsonHelper.getInstance().write(cfgStr), jdbcTemplate);
		if (create == null)
			return null;
		Map<String, Object> createObj = (Map<String, Object>) JsonHelper
				.getInstance().read(create);
		return createObj;
	}

	public static String getDsType(String dsName) {
		try {
			String type = DataSourceHolder.getInstance().getDataSourceType(
					dsName);
			return type;
		} catch (Exception e) {
			LogWriter.addLog("ERROR", "获取数据库类型出错 数据源：{}，异常：{}", dsName,
					e.getMessage());
			return "none";
		}
	}
	public static String getDatasourceType(String driverName){
		String result="";
		if(driverName!=null){
			Pattern pattern = Pattern.compile(DataCollectionUtils.getProperties("dsTypeList"));
			Matcher m = pattern.matcher(driverName.toLowerCase());
			if(m.matches()){
				result = m.group(1);
			}else{
				result = driverName;
			}
		}
		return result;
	}
	public static String getProperties(String propertyName){
		String value=Configuration.getInstance().getProperty(propertyName);
		if(value!=null&&value.length()>0){
			return value;
		}else{
			LogWriter.addLog("ERROR","{}属性未配置",propertyName);
			return "null";
		}
	}
	public static String getProperties(String propertyName,String defaultValue){
		String value=Configuration.getInstance().getProperty(propertyName);
		if(value!=null&&value.length()>0){
			return value;
		}else{
			return defaultValue;
		}
	}
	public static int getIntProperties(String propertyName){
		String value=getProperties(propertyName);
		try{
			return Integer.parseInt(value);
		}catch (Exception e){
			LogWriter.addLog("DEBUG",e.getMessage());
			return 1;
		}
	}

	public static String getXmlId(String dataname, String dsName,
			JdbcTemplate jdbc) {
		String fetchSql = getProperties("fetchTableFileXmlId");
		try {
			Map<String, Object> tableFile = (Map<String, Object>) jdbc
					.queryForMap(fetchSql, new Object[] { dataname, dsName });

			return tableFile.get("xmlId").toString();
		} catch (Exception e) {
			LogWriter.addLog("ERROR", "从tablefile中获取id失败，数据库：{},表名：{},原因：{}",
					dsName, dataname, e.getMessage());
			return "null";
		}
	}
	public static String getTeamCode(String proc_name,JdbcTemplate jdbc){
		String fetchSql =getProperties("fetchTeamCodeInfo");
		try {
			Map<String, Object> tableFile = (Map<String, Object>) jdbc
					.queryForMap(fetchSql, new Object[] { proc_name });

			return tableFile.get("team_code").toString();
		} catch (Exception e) {
			LogWriter.addLog("ERROR", "从proc中获取team_code失败，程序名：{},原因：{}",
					proc_name, e.getMessage());
			return "null";
		}
	}
	public static String getCurrentTimestampByFormate(){
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat(DataCollectionUtils.getProperties("date_format"));
		String time=sdf.format(date);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("time", time);
		String time_model=DataCollectionUtils.getProperties("time_model");
		time=DpExecutorUtils.variableSubstitution(time_model, map);
		return time;
	}
	public static String getCurrentTimestampByFormate(String format){
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		String time=sdf.format(date);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("time", time);
		String time_model=DataCollectionUtils.getProperties("time_model");
		time=DpExecutorUtils.variableSubstitution(time_model, map);
		return time;
	}

	public static String getPropertyFromMap(Map obj,String key){
		if(obj.get(key)!=null&&obj.get(key).toString().length()>0)
			return obj.get(key).toString();
		else{
			LogWriter.addLog("DEBUG","{}属性不存在",key);
			return "null";
		}
	}
}
